﻿using MyFileView.Core;
using MyFileView.Core.Core;

using System.Diagnostics;

using uno.util;

using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;

using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;

namespace MyFleView.Core
{
    public interface IConvertCore : RegisterAutofac
    {
        void CreateComponentContext();
        void Connection();
        void SaveDocument(PropertyValue[] propertyValues);
    }
    public class ConvertCore: IConvertCore//:AbstractOfficeDocumentConvert(convertFileFactory),
    {

        private readonly string _connectionString;
        private XComponent _bridgeComponent;
        private XMultiComponentFactory _serviceManager;
        private XComponentContext _componentContext;
        private XBridge _bridge;
        private bool _connected;
        private bool _expectingDisconnection;
        private XComponent xComponent;
        private ConvertFileContext ConvertFileContext;
        public ConvertCore(IConvertFileFactory convertFileFactory) 
        {
            ConvertFileContext = convertFileFactory.ConvertFileContext;

        }
        /// <summary>
        /// Get a ComponentContext从 UNO 安装引导组件上下文。
        /// </summary>
        public void CreateComponentContext()
        {
            try
            {
                _componentContext = Bootstrap.bootstrap();// Bootstrap.bootstrap();
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("初始化libreoffice连接出错");
            }
        }


        //传递给组件的组件上下文。
        //        public void GetUnoServer() 
        //        {
        //            unoidl.com.sun.star.lang.XMultiServiceFactory xRemoteFactory = (XMultiServiceFactory)_componentContext.getServiceManager();


        //            //这是一个简单的接口，用于通过 URL 将组件加载到框架环境中
        //            /*
        //             com.sun.star.frame.Desktop 服务，与 Apache OpenOffice 的核心服务类似。它为 Apache OpenOffice 框架对象提供了一些功能，可根据这些功能对所有文档窗口进行分类。还可以使用该服务创建、打开和导入文档。
        //单个文档对象的基本功能是由 com.sun.star.document.OfficeDocument 服务提供的。该服务提供了用于保存、导出和打印文档的方法。
        //             */
        //            XComponentLoader aLoader = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");

        //            //Load the sourcefile
        //            /*
        //             创建、打开和导入文档
        //             */
        //            xComponent = aLoader.loadComponentFromURL(filenfo.FullFilePath, "_blank", 0, propertyValue);//new unoidl.com.sun.star.beans.PropertyValue[0]
        //        }
        public void Connection()
        {
            try
            {

              
                //sourcePath = PathConverter(sourcePath);
                //destinationPath = PathConverter(destinationPath);

                // 载入文件前属性设定，设定文件开启时隐藏
                //PropertyValue[] loadDesc = new PropertyValue[1];
                //loadDesc[0] = new PropertyValue();
                //loadDesc[0].Name = "Hidden";
                //loadDesc[0].Value = new uno.Any(true);
                //   XComponentContext localContext = Bootstrap.bootstrap();
                //XComponentContext localContext = Bootstrap.defaultBootstrap_InitialComponentContext();
                //XMultiComponentFactory localServiceManager = localContext.getServiceManager();
                //XConnector connector = (XConnector)localServiceManager.createInstanceWithContext("com.sun.star.connection.Connector", localContext);
                //XConnection connection = connector.connect(_connectionString);
                //XBridgeFactory bridgeFactory = (XBridgeFactory)localServiceManager.createInstanceWithContext("com.sun.star.bridge.BridgeFactory", localContext);
                //_bridge = bridgeFactory.createBridge("", "urp", connection, null);
                //_bridgeComponent = (XComponent)_bridge;
                //_bridgeComponent.addEventListener(this);
                //_serviceManager = (XMultiComponentFactory)_bridge.getInstance("StarOffice.ServiceManager");
                //XPropertySet properties = (XPropertySet)_serviceManager;
                //// Get the default context from the office server. 
                //var oDefaultContext = properties.getPropertyValue("DefaultContext");

                //_componentContext = (XComponentContext)oDefaultContext.Value;
                //_connected = true;
                ////Get a ComponentContext从 UNO 安装引导组件上下文。
                //   unoidl.com.sun.star.uno.XComponentContext xLocalContext = Bootstrap.bootstrap();// Bootstrap.bootstrap();

                //Get MultiServiceFactory
                //传递给组件的组件上下文。
                unoidl.com.sun.star.lang.XMultiServiceFactory xRemoteFactory = (XMultiServiceFactory)_componentContext.getServiceManager();
                // var res = xRemoteFactory.getAvailableServiceNames();
                //Get a CompontLoader

                //这是一个简单的接口，用于通过 URL 将组件加载到框架环境中
                XComponentLoader aLoader = (XComponentLoader)xRemoteFactory.createInstance("com.sun.star.frame.Desktop");

                //Load the sourcefile
                //将 URL 指定的组件加载到指定的新框架或现有框架中。
                xComponent = aLoader.loadComponentFromURL(ConvertFileContext.FileInfo.OfficeFullFilePath, "_blank", 0, ConvertFileContext.DefaultProperties);//new unoidl.com.sun.star.beans.PropertyValue[0]

            }
            catch (System.Exception ex)
            {
                throw new System.Exception("连接libreoffice连接错误" + ex.Message);
                // throw ex;
            }
            finally
            {

                //Process[] pt = Process.GetProcessesByName("soffice.bin");
                //if (pt != null && pt.Length > 0)
                //{
                //    foreach (var item in pt)
                //    {
                //        item.Kill();
                //    }
                //}
                //if (obtained)
                //{
                //    _openOfficeLock.ReleaseMutex();
                //}

            }

        }
        /// <summary>
        /// 执行保存
        /// </summary>
        /// <param name="xComponent">The x component.</param>
        /// <param name="filePath">Name of the file.</param>
        public void SaveDocument( PropertyValue[] propertyValues)
        {
            // var filenfo = ConvertFileContext.FileInfo;
            //unoidl.com.sun.star.beans.PropertyValue[] propertyValue = new unoidl.com.sun.star.beans.PropertyValue[1];

            //propertyValue[0] = new unoidl.com.sun.star.beans.PropertyValue();
            //propertyValue[0].Name = "FilterName";
            //propertyValue[0].Value = new uno.Any("writer_pdf_Export");
            // ((XStorable)xComponent).store();
            try
            {
                var res = ((XStorable)xComponent);
                ((XStorable)xComponent).storeToURL(ConvertFileContext.FileInfo.OfficeOutPutFullFilePath, propertyValues);
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("写入文件失败" + ex.Message);
            }
            finally
            {
                xComponent.dispose();
                Process[] pt = Process.GetProcessesByName("soffice.bin");
                if (pt != null && pt.Length > 0)
                {
                    foreach (var item in pt)
                    {
                        item.Kill();
                    }
                }
                //if (obtained)
                //{
                //    _openOfficeLock.ReleaseMutex();
                //}

            }
        }


    }
}